import ScrollBarLayout from '@/components/ScrollBarLayout';
import { AutoComplete, Card, Col, Empty, Input, Tooltip, Tree } from 'antd';
import { AnnounceManageAPI } from '../common/type';
import { SearchOutlined } from '@ant-design/icons';
import MyIcon from '@/components/MyIcon';
import pageStyles from '@/common/pageLayout.less';
import {
  ChangeEvent,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
} from 'react';
import { AnnounceUpdateContext } from '../common/UpdateContext';
import { loopArray, transltateFn } from '@/utils';
import { IActionEnum } from '../common/UpdateReducer';

export const ReceiveDeptModalLeft: React.FC<AnnounceManageAPI.IReceiveDeptModalLeft> = ({
  leftTreeData,
}) => {
  const {
    dispatch,
    leftSelectKeys,
    leftExpandedKeys,
    leftAutoExpandParent,
  } = useContext(AnnounceUpdateContext);

  const [leftSearchValue, setLeftSearchValue] = useState<string>('');

  // 渲染树数据  Tree
  const orgTreeData = (data: any[]): any[] => {
    let disabled: boolean = false;
    return data?.map((item) => {
      const name =
        item?.text +
        (item?.attributes?.companyName
          ? `（${item?.attributes?.companyName}）`
          : '');
      const nameLength = name?.length;
      const select = name?.search(leftSearchValue);
      const searchLength = leftSearchValue?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = leftSearchValue;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <Tooltip title={name}>
            <span className={pageStyles['over-flow-hidden']}>
              {afterStr}
              <span style={{ color: '#f50' }}>{selectStr}</span>
              {beforeStr}
            </span>
          </Tooltip>
        ) : (
          <Tooltip title={name}>
            <span className={pageStyles['over-flow-hidden']}>
              {name ?? '--'}
            </span>
          </Tooltip>
        );
      // 判断树节点复选框是否可选
      if (item?.textType == 1 && item?.open == true) {
        disabled = false;
      } else {
        disabled = true;
      }
      return {
        ...item,
        title: (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              // paddingRight: 20,
            }}
            id={item?.id + 'receiveCardLeft'}
          >
            {item?.textType == 0 && <MyIcon type={'icon-bank'} />}
            {item?.textType == 1 && <MyIcon type={'icon-cluster'} />}
            {item?.textType == 2 && <MyIcon type={'icon-icon_lingdaopishi'} />}
            &nbsp;
            {titleTree}
          </div>
        ),
        key: item?.id,
        children:
          item?.children && item?.children?.length > 0
            ? orgTreeData(item?.children)
            : null,
        disabled: disabled,
      };
    });
  };

  /**
   * 搜索下拉菜单
   */
  const autoOptionLeft = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.children && item?.children?.length > 0) {
          tileTreeData(item?.children);
        }
        const name =
          item?.text +
          (item?.attributes?.companyName
            ? `（${item?.attributes?.companyName}）`
            : '');
        if (name?.includes(leftSearchValue)) {
          const nameLength = name?.length;
          const select = name?.search(leftSearchValue);
          const searchLength = leftSearchValue?.length;
          const afterStr = name?.slice(0, select);
          const selectStr = leftSearchValue;
          const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: name,
            key: item?.id,
            label: (
              <div>
                <span>{afterStr}</span>
                <span style={{ color: '#f50' }}>{selectStr}</span>
                <span>{beforeStr}</span>
              </div>
            ),
            itemrowobj: { ...item },
          });
        }
      });
    };
    tileTreeData(leftTreeData);
    return option;
  }, [leftTreeData, leftSearchValue]);

  /**
   *  点击搜索
   * @param value
   * @param option
   */
  const onAutoSelectLeft = (value: string, option: any) => {
    // const promise = new Promise((resolve) => {
    const optionId = option?.key;
    const rowObj = option?.itemrowobj;
    const targetNode = loopArray(leftTreeData); //平铺的树
    let openTreeIds = transltateFn(targetNode, rowObj?.pID);
    dispatch({
      type: IActionEnum.LEFTAUTO_PARENT,
      payload: true,
    });
    dispatch({
      type: IActionEnum.LEFTEXPANDED_KEYS,
      payload: openTreeIds,
    });

    setLeftSearchValue(value);

    setTimeout(() => {
      scrollToAnchor(optionId);
    }, 1000);
  };

  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id + 'receiveCardLeft');
    if (id) {
      anchorElement?.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'start',
      });
    }
  };

  /**
   * 搜索框改变
   * @param e
   */
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    setLeftSearchValue(e.target.value);
  };

  /**
   * 保存选中的值
   * @param checkedKeys
   * @param treeNodes
   */
  const onTreeSelect = (checkedKeys: any, treeNodes: any) => {
    dispatch({
      type: IActionEnum.LEFTSELECT_KEYS,
      payload: checkedKeys?.checked,
    });
    dispatch({
      type: IActionEnum.LEFTSELECT_ROW,
      payload: treeNodes?.checkedNodes,
    });
  };

  // 点击展开关闭树
  const onTreeExpand = useCallback(
    (e, a) => {
      dispatch({
        type: IActionEnum.LEFTEXPANDED_KEYS,
        payload: e,
      });
      dispatch({
        type: IActionEnum.LEFTAUTO_PARENT,
        payload: false,
      });
    },
    [leftSelectKeys],
  );

  useEffect(() => {
    if (leftSelectKeys && leftSelectKeys?.length > 0) {
      const treeRows = loopArray(leftTreeData); //平铺的树
      let selectRows: any[] = treeRows?.filter((item: any) => {
        return leftSelectKeys?.includes(item?.id);
      });
      dispatch({
        type: IActionEnum.LEFTSELECT_ROW,
        payload: selectRows,
      });
    }
  }, [leftSelectKeys, leftTreeData]);

  return (
    <>
      <Col span={11}>
        <Card
          bordered
          title={
            <>
              <AutoComplete
                style={{ width: '100%' }}
                options={autoOptionLeft}
                notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                onSelect={onAutoSelectLeft}
              >
                <Input
                  suffix={<SearchOutlined />}
                  onChange={onInputChange}
                  placeholder="请按名称搜索"
                  allowClear
                />
              </AutoComplete>
            </>
          }
        >
          <ScrollBarLayout
            style={{
              height: document.body.clientHeight * 0.4,
              padding: '10px 0px',
            }}
          >
            {leftTreeData && leftTreeData?.length > 0 ? (
              <Tree
                treeData={orgTreeData(leftTreeData)}
                blockNode={true}
                checkable={true}
                autoExpandParent={leftAutoExpandParent}
                onCheck={onTreeSelect}
                checkedKeys={leftSelectKeys}
                expandedKeys={leftExpandedKeys}
                onExpand={onTreeExpand}
                checkStrictly={true}
              />
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </ScrollBarLayout>
        </Card>
      </Col>
    </>
  );
};
